# 标准库
import time
import numpy as np
import pandas as pd

# 可视化的库
import matplotlib.pyplot as plt
import seaborn as sns

# 建模和机器学习
import sklearn.svm as svm
from sklearn.metrics import confusion_matrix,precision_score, classification_report,recall_score
from sklearn.model_selection import train_test_split



train = pd.read_csv(r'G:\ML-homework\fashion-mnist_train.csv (1)\fashion-mnist_train.csv')# 导入训练集 excel表格
test = pd.read_csv(r'G:\ML-homework\fashion-mnist_test.csv (1)\fashion-mnist_test.csv')# 导入测试集 excel表格

# 对标签进行排序并且做出柱状图 查看数据分布
# train['label'].value_counts().sort_index().plot(kind='bar', figsize=(10, 6), rot=0)
# plt.title('Class distribution for the MNIST Dataset', fontsize=20)
# plt.xticks(fontsize=14)
# plt.yticks(fontsize=14)
# plt.xlabel('Class', fontsize=16)
# plt.ylabel('Frequency', fontsize=16)
# plt.show()

# 将训练的数据集的特征和标签对应起来  之后开始划分训练的数据集和验证的数据集
X_train=train.iloc[:,1:]  # 选择所有行和列，但排除列1
Y_train=train['label']  # 将label列作为预测值

# 将测试的数据集的特征和标签对应起来
X_test = test.iloc[:,1:]
Y_test = test['label']



# # 模型核函数的选择
# def svc(kernel):
#     return svm.SVC(kernel=kernel, decision_function_shape="ovr")
#
# def modelist():
#     modelist = []
#     kernalist = {"linear", "poly", "rbf", "sigmoid"}
#     for each in kernalist:
#         modelist.append(svc(each))
#     return modelist
#
#
# def f1_score(precision, recall):
#     score=(2*precision*recall)/(precision+recall)
#     return score
#
#
# def svc_model(model):
#     start_time = time.perf_counter()
#     model.fit(X_train, Y_train)
#     end_time = time.perf_counter()
#     predicition = model.predict(X_test)
#     P = precision_score(Y_test, predicition, average="macro")
#     R = recall_score(Y_test, predicition, average="macro")
#     F1_score = f1_score(P,R)
#     runtime = str(start_time-end_time)
#     return P, R, F1_score, runtime
#
#
# def run_svc_model(modelist):
#     result = {"kernel": [],
#               "P": [],
#               "R": [],
#               "F1_score": [],
#               "runtime": []
#               }
#
#     for model in modelist:
#         P, R, F1_score, runtime = svc_model(model)
#         try:
#             result["kernel"].append(model.kernel)
#         except:
#             result["kernel"].append(None)
#         result["P"].append(P)
#         result["R"].append(R)
#         result["F1_score"].append(F1_score)
#         result["runtime"].append(runtime)
#
#     return pd.DataFrame(result)
#
# run_svc_model(modelist())
#
# #惩罚系数选择
# def test_c():
#     result = {"C": [],
#               "P": [],
#               "R": [],
#               "F1_score": []
#               }
#     for c in range(1, 101, 10):
#         model = svm.SVC(kernel="linear", C=c, decision_function_shape="ovr")
#         P, R, F1_score,runtime = svc_model(model)
#         result["C"].append(c)
#         result["P"].append(P)
#         result["R"].append(R)
#         result["F1_score"].append(F1_score)
#     df = pd.DataFrame(result)
#     return df
# test_c()



# 前面选优工作后模型测试
model = svm.SVC(kernel="linear", decision_function_shape="ovr")
start_time = time.perf_counter()
model.fit(X_train,Y_train) #模型训练
end_time = time.perf_counter()
print("runtime is  " + str(start_time-end_time))
prediction = model.predict(X_test)
plt.figure(figsize=(10,7))
cm = confusion_matrix(Y_test, prediction)
ax = sns.heatmap(cm, annot=True, fmt="d",cmap='Blues')
plt.ylabel('Actual label')  # x轴标题
plt.xlabel('Predicted label')  # y轴标题
plt.show()
print("\ntest Classification Report:")
print(classification_report(Y_test, prediction))